package com.hue.controller;

import com.hue.entity.User;
import com.hue.entity.result.R;
import com.hue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @PostMapping("/doLogin")
    @ResponseBody
    public R doLogin(User user, HttpServletResponse response) {
        Map<String, String> map = userService.login(user);
        if (map.get("error") != null) {
            return R.error().data("error", map.get("error"));
        }
        //将token存在cookie中
        String token = map.get("token");
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        cookie.setDomain("localhost");
        response.addCookie(cookie);
        return R.ok();
    }
}
